#include "stdafx.h"

PropertyMgr::~PropertyMgr()
{
	clear();
}

PropertyMgr * PropertyMgr::getInstance()
{
	static PropertyMgr manager;

	return &manager;
}

void PropertyMgr::draw(Graphics * graphics)
{
	for (Property * p : properties)
	{
		p->draw(graphics);
	}
}

void PropertyMgr::create(const std::wstring & pname, int x, int y)
{
	if (pname == L"Timer")
	{
		properties.push_back(new PropertyTimer(L"timer", x, y));
	}
	else if (pname == L"Star")
	{
		properties.push_back(new PropertyStar(L"star", x, y));
	}
	else if (pname == L"Bomb")
	{
		properties.push_back(new PropertyBomb(L"bomb", x, y));
	}
}

void PropertyMgr::update(double dtime)
{
	time += dtime;

	std::vector<Property *>::iterator p = properties.begin();

	while (p != properties.end())
	{
		(*p)->update(dtime);
		if ((*p)->collide(Game::getInstance()->getHero()->getRect()))
		{
			(*p)->dosomething();
			delete *p;
			p = properties.erase(p);
		}
		else
		{
			p++;
		}
	}

	/*if (time > 40)
	{
		time -= 20;
		Point pt = Map::getInstance()->getVacant(40, 40);

		if (pt.X != -1 && pt.Y != -1)
		{
			switch (rand() % 3)
			{
			case 0:
				create(L"Timer", pt.X, pt.Y);
				break;
			case 1:
				create(L"Bomb", pt.X, pt.Y);
				break;
			case 2:
				create(L"Star", pt.X, pt.Y);
			}
		}
		
	}*/
}

void PropertyMgr::clear()
{
	for (Property * p : properties)
	{
		delete p;
	}

	properties.clear();
}

void PropertyMgr::create(xml_node<wchar_t> * prop)
{
	xml_node<wchar_t> * p = prop->first_node(L"prop");

	while (p)
	{
		std::wstring name = p->first_node(L"name")->value();
		int x = _wtoi(p->first_node(L"x")->value()) + LEFTMAP;
		int y = _wtoi(p->first_node(L"y")->value()) + TOPMAP;

		create(name, x, y);

		p = p->next_sibling();
	}
}